package xyz.yang.persistence.mongo.core;

import com.mongodb.client.MongoClient;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.mongo.MongoConnectionDetails;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.MongoDatabaseFactorySupport;
import org.springframework.data.mongodb.core.MongoTemplate;
import xyz.yang.persistence.mongo.core.multipletenant.SimpleMongoClientMultiDatabaseFactory;

/**
 * @author Xuehong Yang
 * @since 1.0
 */

@AutoConfiguration
@SuppressWarnings("unused")
public class MongoAutoConfiguration {
    @Bean
    public MongoPageHelper mongoPageHelper(MongoTemplate mongoTemplate) {
        return new MongoPageHelper(mongoTemplate);
    }

    @Bean
    @ConditionalOnProperty(prefix = "xyz.yang.transaction", name = "support-transaction", matchIfMissing = false)
    MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

    @Bean
    @ConditionalOnProperty(prefix = "xyz.yang.mongo.multi-tenant", name = "isolation-mode", havingValue = "database")
    MongoDatabaseFactorySupport<?> mongoDatabaseFactory(MongoClient mongoClient, MongoProperties properties,
                                                        MongoConnectionDetails connectionDetails) {
        String database = properties.getDatabase();
        if (database == null) {
            database = connectionDetails.getConnectionString().getDatabase();
        }
        return new SimpleMongoClientMultiDatabaseFactory(mongoClient, database);
    }
}
